import 'package:flutter/material.dart';
import 'package:flutter_openim_sdk/flutter_openim_sdk.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:openim/core/controller/im_controller.dart';
import 'package:openim_common/openim_common.dart';
import 'package:sprintf/sprintf.dart';

import 'conversation_logic.dart';

class ConversationPage extends StatelessWidget {
  final logic = Get.find<ConversationLogic>();
  final im = Get.find<IMController>();

  ConversationPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Obx(() => Scaffold(
          backgroundColor: Styles.c_F8F9FA,
          appBar: TitleBar.conversation(
              statusStr: logic.imSdkStatus,
              isFailed: logic.isFailedSdkStatus,
              popCtrl: logic.popCtrl,
              onAddFriend: logic.addFriend,
              // onAddGroup: logic.addGroup,
              onCreateGroup: logic.createGroup,
              onScan: logic.scan,
              onSearch: logic.globalSearch,
              left: Expanded(
                flex: 2,
                child: Row(
                  mainAxisSize: MainAxisSize.max,
                  children: [
                    AvatarView(
                      width: 42.w,
                      height: 42.h,
                      text: im.userInfo.value.nickname,
                      url: im.userInfo.value.faceURL,
                    ),
                    10.horizontalSpace,
                    if (null != im.userInfo.value.nickname)
                      Flexible(
                        child: im.userInfo.value.nickname!.toText
                          ..style = Styles.ts_0C1C33_17sp
                          ..maxLines = 1
                          ..overflow = TextOverflow.ellipsis,
                      ),
                    10.horizontalSpace,
                    if (null != logic.imSdkStatus && (!logic.reInstall || logic.isFailedSdkStatus))
                      Flexible(
                          child: SyncStatusView(
                        isFailed: logic.isFailedSdkStatus,
                        statusStr: logic.imSdkStatus!,
                      )),
                  ],
                ),
              )),
          body: Column(
            children: [
              Expanded(
                  child: ListView.builder(
                    itemBuilder: (_, index) => _buildItemView(
                      logic.list.elementAt(index),
                    ),
                    itemCount: logic.list.length,
                  
                ),
              ),
            ],
          ),
        ));
  }
    Widget _buildItemView(ConversationInfo info) {
    return Container(
      height: 68.h,
      child: Stack(
        children: [
          // 背景操作按钮层
          Positioned.fill(
            child: Container(
              color: Styles.c_F8F9FA,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  Row(children: [
                    GestureDetector(
                      onTap: () {
                        logic.pinConversation(info);
                      },
                      child: Container(
                        width: 80.w,
                        height: 68.h,
                        color: const Color(0xFF007AFF), // 蓝色
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Icon(
                              info.isPinned == true ? Icons.push_pin : Icons.push_pin_outlined,
                              color: Colors.white,
                              size: 20.w,
                            ),
                            4.verticalSpace,
                            (info.isPinned == true ? '取消置顶' : '置顶').toText..style = Styles.ts_FFFFFF_12sp,
                          ],
                        ),
                      ),
                    ),
                    // 不显示按钮（橙色）
                    GestureDetector(
                      onTap: () {
                        logic.hideConversation(info);
                        logic.resetSlideState(info.conversationID);
                      },
                      child: Container(
                        width: 80.w,
                        height: 68.h,
                        color: const Color(0xFFFF9500), // 橙色
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Icon(
                              Icons.visibility_off,
                              color: Colors.white,
                              size: 20.w,
                            ),
                            4.verticalSpace,
                            '不显示'.toText..style = Styles.ts_FFFFFF_12sp,
                          ],
                        ),
                      ),
                    ),
                    // 删除按钮（红色）
                    GestureDetector(
                    onTap: () {
                      logic.deleteConversation(info);
                      logic.resetSlideState(info.conversationID);
                    },
                    child: Container(
                      width: 80.w,
                      height: 68.h,
                      color: const Color(0xFFE03D32), // 红色
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Icon(
                            Icons.delete,
                            color: Colors.white,
                            size: 20.w,
                          ),
                          4.verticalSpace,
                          '删除'.toText..style = Styles.ts_FFFFFF_12sp,
                        ],
                      ),
                    ),
                  ),]
                ),
                ],
              ),
            ),
          ),
          // 主内容层 - 使用 Transform + GetBuilder
          GetBuilder<ConversationLogic>(
            id: 'slide_${info.conversationID}', // 精确更新指定会话
            builder: (logic) {
              return Transform.translate(
                offset: Offset(logic.getDragOffset(info.conversationID), 0),
                child: GestureDetector(
                  // 拖动开始
                  onPanStart: (details) {
                    print('开始拖动: ${info.conversationID}');
                    logic.startDrag(info.conversationID);
                  },
                  // 拖动过程中
                  onPanUpdate: (details) {
                    // 实时更新拖动偏移量
                    logic.updateDrag(info.conversationID, details.delta.dx);
                  },
                  // 拖动结束
                  onPanEnd: (details) {
                    print('拖动结束: ${info.conversationID}, 速度: ${details.velocity.pixelsPerSecond.dx}');
                    logic.endDrag(info.conversationID, details.velocity.pixelsPerSecond.dx);
                  },
                  // 点击事件
                  onTap: () {
                    print('点击事件: ${info.conversationID}, 当前滑动状态: ${logic.isSlided(info.conversationID)}');
                    // 如果当前item已经滑动，点击时重置状态
                    if (logic.isSlided(info.conversationID)) {
                      logic.resetSlideState(info.conversationID);
                      return;
                    }
                    
                    // 如果有其他item处于滑动状态，先重置所有状态
                    logic.resetAllSlideStates();
                    
                    // 进入聊天
                    logic.toChat(conversationInfo: info);
                  },
                  child: Container(
                    height: 68.h,
                    padding: EdgeInsets.symmetric(horizontal: 16.w),
                    color: Styles.c_FFFFFF,
                    child: Row(
                      children: [
                        Stack(
                          children: [
                            AvatarView(
                              width: 48.w,
                              height: 48.h,
                              text: logic.getShowName(info),
                              url: info.faceURL,
                              isGroup: logic.isGroupChat(info),
                              textStyle: Styles.ts_FFFFFF_14sp_medium,
                            ),
                          ],
                        ),
                        12.horizontalSpace,
                        Expanded(
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Row(
                                children: [
                                  ConstrainedBox(
                                    constraints: BoxConstraints(maxWidth: 180.w),
                                    child: logic.getShowName(info).toText
                                      ..style = Styles.ts_0C1C33_17sp
                                      ..maxLines = 1
                                      ..overflow = TextOverflow.ellipsis,
                                  ),
                                  const Spacer(),
                                  logic.getTime(info).toText..style = Styles.ts_8E9AB0_12sp,
                                ],
                              ),
                              3.verticalSpace,
                              Row(
                                children: [
                                  MatchTextView(
                                    text: logic.getContent(info),
                                    textStyle: Styles.ts_8E9AB0_14sp,
                                    prefixSpan: TextSpan(
                                      text: '',
                                      children: [
                                        if (logic.getUnreadCount(info) > 0)
                                          TextSpan(
                                            text: '[${sprintf(StrRes.nPieces, [logic.getUnreadCount(info)])}] ',
                                            style: Styles.ts_8E9AB0_14sp,
                                          ),
                                        TextSpan(
                                          text: logic.getPrefixTag(info),
                                          style: Styles.ts_0089FF_14sp,
                                        ),
                                      ],
                                    ),
                                    maxLines: 1,
                                    overflow: TextOverflow.ellipsis,
                                  ),
                                  const Spacer(),
                                  UnreadCountView(count: logic.getUnreadCount(info)),
                                ],
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              );
            },
          ),
        ],
      ),
    );
  }
}